//
//  DataHandle.m
//  DayByDay
//
//  Created by dllo on 16/5/28.
//  Copyright © 2016年 dllo. All rights reserved.
//

#import "DataHandle.h"
#import "FMDB.h"

@interface DataHandle ()

@property (nonatomic, strong)FMDatabase *fmdb;

@end

@implementation DataHandle


+ (instancetype)shareDataBaseHandle {
    static DataHandle *dataHandle = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        dataHandle = [[DataHandle alloc] init];
    });
    return dataHandle;
}

- (void)openDB {
    NSString *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject;
    NSString *filePath = [path stringByAppendingPathComponent:@"DayByDay.sqlite"];
    NSLog(@"%@",filePath);
    self.fmdb = [[FMDatabase alloc] initWithPath:filePath];
    BOOL result = [self.fmdb open];
    if (result) {
        NSLog(@"打开成功");
    } else {
        NSLog(@"打开失败");
    }
}

- (void)exeSqlWith:(NSString *)sql showLog:(NSString *)log {
    //使用fmdb执行sql语句
    BOOL result = [self.fmdb executeUpdate:sql];
    
    if (result) {
        NSLog(@"%@",[NSString stringWithFormat:@"%@成功",log]);
    }else {
        NSLog(@"%@",[NSString stringWithFormat:@"%@失败", log]);
    }
    
    
}

- (void)createTableWithName:(NSString *)name {
    NSString *sqlStr = [NSString stringWithFormat:@"create table if not exists '%@'(songId text primary key, name text, singerId text, singerName text, picUrl text, url text)",name];
    [self exeSqlWith:sqlStr showLog:@"创建表"];
}

- (void)insertPosterSongsModel:(PosterDetailSongsModel *)model initoTable:(NSString *)table{
    AuditionListModel *listModel = model.auditionList.lastObject;
    NSString *sql = [NSString stringWithFormat:@"insert into '%@'(songId ,name, singerId, singerName, picUrl, url) values ('%@', '%@', '%@', '%@', '%@', '%@')", table, model.songId, model.name, model.singerId, model.singerName, model.picUrl, listModel.url];
    [self exeSqlWith:sql showLog:@"插入数据"];
}

- (void)deletePosterSongsModel:(PosterDetailSongsModel *)model intoTable:(NSString *)table {
    AuditionListModel *listModel = model.auditionList.lastObject;
    NSString *sql = [NSString stringWithFormat:@"delete from '%@' where url = '%@'", table, listModel.url];
    [self exeSqlWith:sql showLog:@"删除数据"];
}

- (BOOL)selectPosterSongsModelFromTable:(NSString *) table PrimaryKey:(NSString *)primary{
    NSString *sql = [NSString stringWithFormat:@"select * from '%@'",table];
    FMResultSet *set = [self.fmdb executeQuery:sql];
    //执行查询语句
    //FMResultSet 的作用就是遍历表里符合数据的每一行
    while ([set next]) {
//        NSString *
//        songId ,name, singerId, singerName, picUrl, url
        NSString *urlStr = [set stringForColumn:@"songId"];
        
        if ([primary isEqualToString:urlStr]) {
            return YES;
        }
    }
    return NO;
}

- (NSMutableArray *)selectPosterSongsModelFromTable:(NSString *) table {
    NSMutableArray *array = [NSMutableArray array];
    NSString *sql = [NSString stringWithFormat:@"select * from '%@'",table];
    FMResultSet *set = [self.fmdb executeQuery:sql];
    while ([set next]) {
        PosterDetailSongsModel *model = [PosterDetailSongsModel new];
        //        songId ,name, singerId, singerName, picUrl, url
        model.songId =[NSNumber numberWithInteger:[[set stringForColumn:@"songId"] integerValue]];
//        model.singerId = [NSNumber numberWithInteger:[[set stringForColumn:@"singId"] integerValue]];
        model.name = [set stringForColumn:@"name"];
        model.singerName = [set stringForColumn:@"singerName"];
        model.picUrl = [set stringForColumn:@"picUrl"];
        model.auditionList = [NSMutableArray array];
        AuditionListModel *listModel = [AuditionListModel new];
        listModel.url = [set stringForColumn:@"url"];
        [model.auditionList addObject:listModel];
        [array addObject:model];
    }
    return array;
}


- (void)dropTable:(NSString *)table {
    NSString *sqlstr = [NSString stringWithFormat:@"drop table %@", table];
    [self exeSqlWith:sqlstr showLog:@"删除表"];
}

- (void)insertMany:(NSMutableArray<PosterDetailSongsModel *>*)array intoTable:(NSString *)table{
    //创建fmdb多线程队列对象,实现将多个插入操作放在子线程去完成,加快运行速度
    NSString *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject;
    NSString *filePath = [path stringByAppendingPathComponent:@"DayByDay.sqlite"];
//    FMDatabaseQueue *queue = [FMDatabaseQueue databaseQueueWithPath:filePath];
    //将添加Model的操作放到FMDB的事务中去完成
    //Transaction 事务
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        for (PosterDetailSongsModel *model in array) {
            
            [self insertPosterSongsModel:model initoTable:table];
            
        }
        
    });
//    for (PosterDetailSongsModel *model in array) {
//        
//        [self insertPosterSongsModel:model initoTable:table];
//        
//    }

//    [queue inTransaction:^(FMDatabase *db, BOOL *rollback) {
//        for (PosterDetailSongsModel *model in array) {
//            [self insertPosterSongsModel:model initoTable:table];
//        }
//        
//    }];
//    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//        for (PosterDetailSongsModel *model in array) {
//            [queue inTransaction:^(FMDatabase *db, BOOL *rollback) {
//                
//               db executeUpdate:<#(NSString *), ...#>
//            }];
//        }
//        
//    });
    
}

@end
